<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个组件 -->
        <tree-tools :tree-node="company" :is-root="true" @addDepts="addDepts" />
        <el-tree :data="departs" :props="defaultProps">
          <!-- el-tree 的插槽内容 会被循环 有多少个节点就会循环生成多少次 -->
          <template v-slot="{data}">
            <TreeTools :tree-node="data" @delDepts="getDepartments" @addDepts="addDepts" @deitDepts="deitDepts" />
          </template>
          <!-- 先执行作用插槽的赋值再执行porps传值 -->
        </el-tree>
      </el-card>
    </div>
    <add-dept ref="addDept" :show-dialog.sync="showDialog" :tree-node="node" @addDepts="getDepartments" />
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import { getDepartments } from '@/api/departments'
import { transListTreeData } from '@/utils'
import AddDept from './components/add-dept.vue'

export default {
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      departs: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      company: {},
      showDialog: false,
      node: null, // 用来记录将来要添加的子部门
      loading: false
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      this.loading = true
      const result = await getDepartments()
      this.departs = transListTreeData(result.depts, '')
      this.company = {
        name: result.companyName,
        manager: '负责人',
        id: '' // 匹配pid为''的时候
      }
      await new Promise(resolve => setTimeout(() => resolve(), 200))
      this.loading = false
    },
    addDepts(node) { // 新增弹层打开,并记录当前的节点
      this.showDialog = true // xiangshi
      this.node = node
    },
    deitDepts(node) {
      this.showDialog = true
      this.node = node
      this.$refs.addDept.getDepartDetail(node.id)
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
